import React, { useState, useEffect } from 'react';
import {
  Card,
  Button,
  Space,
  Switch,
  Typography,
  Divider,
  Tooltip,
  Badge
} from 'antd';
import {
  SettingOutlined,
  InfoCircleOutlined,
  AppstoreOutlined
} from '@ant-design/icons';
import styled from 'styled-components';
import { ExtensionSettings, MessageType } from '../types';
import './popup.less';

const { Title, Text } = Typography;

const PopupCard = styled(Card)`
  margin-bottom: 0;
`

const Popup: React.FC = () => {
  const [settings, setSettings] = useState<ExtensionSettings>({
    theme: 'light',
    language: 'zh-CN',
    autoUpdate: true,
    enableNotifications: true
  });
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      const result = await chrome.storage.sync.get(['settings']);
      if (result.settings) {
        setSettings(result.settings);
      }
    } catch (error) {
      console.error('Failed to load settings:', error);
    }
  };

  const handleSettingChange = async (key: keyof ExtensionSettings, value: any) => {
    const newSettings = { ...settings, [key]: value };
    setSettings(newSettings);

    try {
      await chrome.storage.sync.set({ settings: newSettings });
      // 通知背景脚本设置已更新
      console.log('Popup: Sending UPDATE_SETTINGS message', newSettings);
      chrome.runtime.sendMessage({
        type: MessageType.UPDATE_SETTINGS,
        payload: newSettings
      }, (response) => {
        console.log('Popup: Received response from background:', response);
        if (chrome.runtime.lastError) {
          console.error('Popup: Chrome runtime error:', chrome.runtime.lastError);
        }
      });
    } catch (error) {
      console.error('Failed to save settings:', error);
    }
  };

  const openSettingsPage = () => {
    chrome.runtime.openOptionsPage();
  };

  const toggleSidePanel = async () => {
    try {
      setLoading(true);
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tab.id) {
        await chrome.sidePanel.open({ tabId: tab.id });
      }
    } catch (error) {
      console.error('Failed to open side panel:', error);
    } finally {
      setLoading(false);
    }
  };

  const toggleFloatBox = () => {
    console.log('Popup: Sending TOGGLE_FLOAT_BOX message');
    chrome.runtime.sendMessage({
      type: MessageType.TOGGLE_FLOAT_BOX
    }, (response) => {
      console.log('Popup: Received response from background:', response);
      if (chrome.runtime.lastError) {
        console.error('Popup: Chrome runtime error:', chrome.runtime.lastError);
      }
    });
  };

  return (
    <div className="popup-container">
      <PopupCard
        variant="borderless"
        title={
          <Space>
            <AppstoreOutlined />
            <Title level={4} style={{ margin: 0 }}>
              Chrome 扩展
            </Title>
          </Space>
        }
        extra={
          <Tooltip title="打开设置页面">
            <Button
              type="text"
              icon={<SettingOutlined />}
              onClick={openSettingsPage}
            />
          </Tooltip>
        }
      >
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          {/* 快速功能区 */}
          <div className="function-section">
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                <Text>侧边栏</Text>
                <Button
                  type="primary"
                  size="small"
                  loading={loading}
                  onClick={toggleSidePanel}
                >
                  打开
                </Button>
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                <Text>悬浮框</Text>
                <Button
                  type="default"
                  size="small"
                  onClick={toggleFloatBox}
                >
                  切换
                </Button>
              </div>
            </Space>
          </div>

          <Divider style={{ margin: '8px 0' }} />

          {/* 快速设置区 */}
          <div className="settings-section">
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                <Text>深色主题</Text>
                <Switch
                  checked={settings.theme === 'dark'}
                  onChange={(checked) =>
                    handleSettingChange('theme', checked ? 'dark' : 'light')
                  }
                />
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                <Text>自动更新</Text>
                <Switch
                  checked={settings.autoUpdate}
                  onChange={(checked) => handleSettingChange('autoUpdate', checked)}
                />
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
                <Text>通知</Text>
                <Badge dot={settings.enableNotifications}>
                  <Switch
                    checked={settings.enableNotifications}
                    onChange={(checked) => handleSettingChange('enableNotifications', checked)}
                  />
                </Badge>
              </div>
            </Space>
          </div>

          <Divider style={{ margin: '8px 0' }} />

          {/* 信息区 */}
          <div className="info-section">
            <Space>
              <InfoCircleOutlined style={{ color: '#1890ff' }} />
              <Text type="secondary" style={{ fontSize: '12px' }}>
                版本 1.0.0
              </Text>
            </Space>
          </div>
        </Space>
      </PopupCard>
    </div>
  );
};

export default Popup;

